package cn.com.stary1993.kite.captcha.support.behavior.secondary;

import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cn.com.stary1993.kite.captcha.config.BehaviorImageCaptchaProperties.SecondaryVerificationProperties;
import cn.com.stary1993.kite.captcha.support.behavior.BehaviorImageCaptcha;
import cn.com.stary1993.kite.captcha.support.behavior.FilterBehaviorImageCaptcha;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 二次验证
 *
 * @author stary1993
 */
public class BehaviorImageCaptchaSecondaryVerification extends FilterBehaviorImageCaptcha {

    private SecondaryVerificationProperties prop;

    public BehaviorImageCaptchaSecondaryVerification(BehaviorImageCaptcha target,
                                                     SecondaryVerificationProperties prop) {
        super(target);
        this.prop = prop;
    }

    @Override
    public ApiResponse<?> matching(String id, ImageCaptchaTrack imageCaptchaTrack) {
        ApiResponse<?> match = super.matching(id, imageCaptchaTrack);
        if (match.isSuccess()) {
            // 如果匹配成功， 添加二次验证记录
            addSecondaryVerification(id);
        }
        return match;
    }

    /**
     * 二次缓存验证
     *
     * @param id id
     * @return boolean
     */
    public boolean secondaryVerification(String id) {
        Map<String, Object> cache = (Map<String, Object>) target.getCacheStore().getAndRemoveCache(getKey(id));
        return cache != null;
    }

    /**
     * 添加二次缓存验证记录
     *
     * @param id id
     */
    protected void addSecondaryVerification(String id) {
        target.getCacheStore().setCache(getKey(id), Collections.emptyMap(), prop.getExpire(), TimeUnit.MILLISECONDS);
    }

    protected String getKey(String id) {
        return prop.getKeyPrefix().concat(":").concat(id);
    }

}
